package com.hwpt.hwaccount.core.utils;

import android.content.Context;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;

import java.security.KeyStore;
import java.security.SecureRandom;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class SecurityUtils {
    private static final String ANDROID_KEYSTORE = "AndroidKeyStore";
    private static final String KEY_ALIAS = "hanwang_account_db_key";
    
    public static byte[] getDatabasePassphrase(Context context) {
        try {
            // 从Android KeyStore获取或生成密钥
            KeyStore keyStore = KeyStore.getInstance(ANDROID_KEYSTORE);
            keyStore.load(null);
            
            if (!keyStore.containsAlias(KEY_ALIAS)) {
                // 生成新的密钥
                KeyGenerator keyGenerator = KeyGenerator.getInstance(
                        KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE);
                
                keyGenerator.init(new KeyGenParameterSpec.Builder(
                        KEY_ALIAS,
                        KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                        .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
                        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                        .setRandomizedEncryptionRequired(false)
                        .build());
                
                keyGenerator.generateKey();
            }
            
            // 获取密钥
            SecretKey secretKey = (SecretKey) keyStore.getKey(KEY_ALIAS, null);
            return secretKey.getEncoded();
        } catch (Exception e) {
            // 如果KeyStore操作失败，使用一个安全的随机值作为回退方案
            byte[] fallbackKey = new byte[32];
            new SecureRandom().nextBytes(fallbackKey);
            return fallbackKey;
        }
    }
    
    public static String getCurrentUserId(Context context) {
        // 实际应用中应该从登录状态或SharedPreferences/DataStore中获取
        return "default_user_id";
    }
}